﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem.Layouts;
using UnityEngine.InputSystem.OnScreen;
using UnityEngine;

namespace BlockOS.Client.GUI
{
    public class OnScreenLever : OnScreenControl, IPointerDownHandler, IPointerUpHandler, IDragHandler
    {
        [SerializeField]
        private RectTransform m_HandleTransform;

        [InputControl(layout = "Axis")]
        [SerializeField]
        private string m_ControlPath;

        private RectTransform m_rectTransform;
        public RectTransform rectTransform
        {
            get
            {
                if (m_rectTransform == null)
                {
                    m_rectTransform = GetComponent<RectTransform>();
                }
                return m_rectTransform;
            }
        }

        private Vector2 m_StartPos;
        private float m_Value;
        private bool m_Dragging;
        private float movementRange;

        protected override string controlPathInternal
        {
            get => m_ControlPath;
            set => m_ControlPath = value;
        }

        private void Start()
        {
            m_StartPos = m_HandleTransform.localPosition;
            movementRange = rectTransform.rect.height / 2.0f;
        }

        private void Update()
        {
            if (m_Dragging)
            {
                SendValueToControl(m_Value);
            }
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            m_HandleTransform.localPosition = m_StartPos;
            m_Dragging = false;
            SentDefaultValueToControl();
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            if (eventData == null)
                throw new System.ArgumentNullException(nameof(eventData));

            if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out var position)) return;

            m_Dragging = true;
            OnLever(eventData);
        }

        public void OnDrag(PointerEventData eventData)
        {
            if (eventData == null)
                throw new System.ArgumentNullException(nameof(eventData));

            OnLever(eventData);
        }

        private void OnLever(PointerEventData eventData)
        {
            RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out var position);
            var delta = position - m_StartPos;

            delta.x = 0;
            delta.y = Mathf.Clamp(delta.y, -movementRange, movementRange);
            
            m_HandleTransform.localPosition = m_StartPos + delta;

            m_Value = delta.y / movementRange;
            //Debug.Log(value);
            SendValueToControl(m_Value);
        }
    }
}
